<template>
  <el-card class="box-card">
   <bread data1='用户管理' data2='用户列表'></bread>

    <el-row style="margin-top:20px">
      <!-- 搜索 -->
      <el-col>
        <el-input
          placeholder="请输入用户名"
          v-model="query"
          class="inputselect"
          clearable
          @clear="handleClear"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="searchUser"
          ></el-button>
        </el-input>
        <!-- 添加用户 -->
        <el-button
          type="success"
          icon="el-icon-user"
          class="addusers"
          @click="dialogFormVisibleAdd = true"
          >添加用户</el-button
        >
      </el-col>
      <el-table :data="userlist" style="width: 100%">
        <el-table-column type="index" label="#" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="80">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width=""> </el-table-column>
        <el-table-column prop="mobile" label="电话" width=""> </el-table-column>
        <el-table-column label="创建日期" width="100">
          <!--在这个ui库中 创建template标签，但是由于相当于一个新的组件所以无法访问到el-table-column里面的数据
        可以在template添加 v-slot='数据源'来获取 slot-scope 已经废弃
        userlist.row 是数组的每一个对象
          -->
          <template v-slot="userlist">
            {{ userlist.row.create_time | fmtdate }}
          </template>
        </el-table-column>
        <el-table-column label="用户状态" width="">
          <template v-slot="userlist">
            <el-switch
              v-model="userlist.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="flagUser(userlist.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="">
          <template v-slot="scope">
            <el-row>
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                plain
                @click="editorUser(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                plain
                @click="deluser(scope.row.id)"
              ></el-button>
              <el-button
                type="success"
                icon="el-icon-check"
                circle
                size="mini"
                plain
                @click="setUser(scope.row)"
              ></el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="2"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 对话框 -->
    <!--添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisibleAdd">
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input
            v-model="form.password"
            autocomplete="off"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 用户信息修改对话框 -->
    <el-dialog title="添加用户" :visible.sync="editorShow">
      <el-form :model="editorForm">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input
            v-model="editorForm.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="editorForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="editorForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editorShow = false">取 消</el-button>
        <el-button type="primary" @click="handleEditor">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改当前用户的角色 -->
    <el-dialog title="修改用户角色" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="用户名" label-width="100px">
          {{ currentUsername }}
        </el-form-item>
        <el-form-item label="角色" label-width="100px">
          <!--如果select绑定的值 和option的value的值一样就会显示该option的label的值  -->
          <el-select v-model="currentRoleId">
            <el-option label="请选择" :value="-1" disabled></el-option>
            <el-option v-for="item in userArr"  :key="item.id" :label="item.roleName" :value="item.id" ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserRole"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
export default {
  data () {
    return {
      query: '', // 通过绑定的值 来获取对应的用户
      pagenum: 1, // 从第几页开始
      pagesize: 2, // 每页有几个
      total: -1, // 总数
      // 表格中的数据
      userlist: [],
      // 添加对话框属性
      dialogFormVisibleAdd: false,
      editorShow: false,
      formLabelWidth: '120px',
      dialogTableVisible: false,
      dialogFormVisible: false,
      currentRoleId: -1,
      currentId: 0,
      currentUsername: '',
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editorForm: {},
      userArr: []
    }
  },
  created () {
    this.getUserlist()
  },
  methods: {
    // 修改用户角色确定
    async setUserRole () {
      // console.log(this.currentRoleId)
      const res = await this.$http.put(`users/${this.currentId}/role`, {
        rid: this.currentRoleId
      })
      const {
        meta: { msg, status }
      } = res.data
      if (status === 200) {
        this.dialogFormVisible = false
        this.$message.success(msg)
        this.getUserlist()
      } else {
        this.$message.error(msg)
      }
    },
    // 修改用户角色
    async setUser (user) {
      this.currentUsername = user.username
      this.dialogFormVisible = true
      const res = await this.$http.get(`users/${user.id}?id=${user.id}`)
      const res1 = await this.$http.get('roles')
      this.currentRoleId = res.data.data.rid
      this.currentId = res.data.data.id
      this.userArr = res1.data.data
      console.log(res1)
      console.log(res)
    },
    // 修改用户状态
    async flagUser (users) {
      // console.log(users);
      const res = await this.$http.put(
        `users/${users.id}/state/${users.mg_state}`,
        users
      )
      const {
        meta: { msg, status }
      } = res.data
      if (status === 200) {
        this.$message.success(msg)
      } else {
        this.$message.error(msg)
      }
    },
    // 添加用户
    async addUser () {
      this.dialogFormVisibleAdd = false
      const res = await this.$http.post('users', this.form)
      const {
        meta: { msg, status }
      } = res.data
      if (status === 201) {
        this.$message.success(msg)
        this.getUserlist()
        for (const i in this.form) {
          this.form[i] = ''
        }
      } else {
        this.$message.warning(msg)
      }
    },
    // 修改用户信息
    editorUser (user) {
      this.editorShow = true
      this.editorForm = user
    },
    async handleEditor () {
      //  let token = localStorage.getItem("token");
      const res = await this.$http.put(
        `users/${this.editorForm.id}`,
        this.editorForm)
      const {
        meta: { msg, status }
      } = res.data
      if (status === 200) {
        this.editorShow = false
        this.$message.success(msg)
      } else {
        this.$message.warning(msg)
      }
    },
    // 删除用户
    deluser (userId) {
      this.$confirm('是否删除改用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$http.delete(`users/${userId}`)
          const {
            meta: { msg, status }
          } = res.data
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.pagenum = 1
            this.getUserlist()
          } else {
            this.$message.error(msg)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索用户
    searchUser () {
      if (!this.query) {
        this.$message.error('输入的用户名不能为空')
        return
      }
      this.getUserlist()
    },
    // 清空输入框内容，重新加载内容
    handleClear () {
      this.getUserlist()
    },
    handleSizeChange (val) {
      // pagesize 每页条数改变的时候触发 val 每页条数
      // console.log(`每页 ${val} 条`);
      this.pagesize = val
      this.getUserlist()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`);
      this.pagenum = val
      this.getUserlist()
    },
    async getUserlist () {
      const res = await this.$http.get(`users?query=${this.query}&pagenum=${this.pagenum}&pagesize=${this.pagesize}`
      )
      const {
        meta: { status },
        data: { users, total }
      } = res.data
      // console.log(users);
      if (status === 200) {
        this.userlist = users
        this.total = total
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  height: 100%;
}
.inputselect {
  width: 330px;
}
.addusers {
  margin-left: 5px;
}
</style>
